﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
using WooCoo.Extension;

namespace WooCoo.Data.DataProvider
{
    public class SqlServerProvider : IDataProvider
    {
        private static readonly Regex ReParameterName = new Regex(@"{(?<number>\d+)}", RegexOptions.Compiled);
        public string DbParmChar
        {
            get { return "@"; }
        }

        public IDataParameter CreateParameter(string parameterName, object value, ParameterDirection direction)
        {
            System.Data.SqlClient.SqlParameter sp = new System.Data.SqlClient.SqlParameter();
            sp.ParameterName = parameterName;
            if (value == null)
            {
                sp.Value = DBNull.Value;
            }
            else
            {
                sp.Value = value;
                sp.DbType = value.GetType().GetDbType();
            }
            sp.Direction = direction;
            return sp;
        }

        public IDataParameter CreateParameter(string parameterName, object value, Type type, ParameterDirection direction, int size)
        {
            System.Data.SqlClient.SqlParameter sp = new System.Data.SqlClient.SqlParameter();
            sp.ParameterName = parameterName;
            if (value == null)
            {
                sp.Value = DBNull.Value;
            }
            else
            {
                sp.Value = value;                
            }
            sp.DbType = type.GetDbType();
            if (size != -1)
                sp.Size = size;
            sp.Direction = direction;
            return sp;
        }

        public string FormatSql(string commonSql, int startIndex)
        {
            if (startIndex == 0)
                return ReParameterName.Replace(commonSql, "@P${number}");
            else
                return ReParameterName.Replace(commonSql, m => { return "@P" + (Convert.ToInt32(m.Value) + startIndex).ToString(); });

        }


        public string ResolveToSqlString(object value)
        {
            switch (value.GetType().GetDbType())
            {
                case DbType.DateTime:
                    //时间类型由于比较灵活,需要处理时间格式
                    if (!(value is DateTime))
                        //DateTime dt = (DateTime)value;                    
                        new NotSupportedException("CannotResolvedSQL");
                    return string.Format("'{0}'", ((DateTime)value).ToString("yyyy.MM.dd HH:mm:ss"));
                case DbType.Int16:
                case DbType.Int32:
                case DbType.Decimal:
                case DbType.Double:                
                    return value.ToString();
                case DbType.String:
                case DbType.Binary:
                case DbType.Guid:
                    return string.Format("'{0}'", value.ToString());
                default:
                    throw new NotSupportedException("CannotResolvedSQL");
            }
        }

        //private string BuildPagingSql()
        //{
        //    StringBuilder sb = new StringBuilder();
        //    sb.Append("WITH pageobject AS ");
        //    sb.AppendFormat("(SELECT {0},", _cols);
        //    sb.AppendFormat("        ROW_NUMBER() OVER (ORDER BY {0}) as RowNumber ", string.IsNullOrEmpty(_orderby) ? _fistField : _orderby);
        //    sb.AppendFormat("   FROM {0}(nolock)", _tableName);
        //    sb.AppendFormat("  WHERE {0} )", string.IsNullOrEmpty(_where) ? " 1=1 " : _where);
        //    sb.AppendFormat("SELECT TOP {0} {1} FROM pageobject", _paging.PageSize, _cols);
        //    sb.AppendFormat(" WHERE RowNumber >{0}", _paging.PageSize * (_paging.PageIndex - 1));
        //    sb.AppendFormat(" ORDER BY {0}", string.IsNullOrEmpty(_orderby) ? _fistField : _orderby);
        //    sb.Append(";");
        //    sb.Append("SELECT COUNT(*) AS [value]");
        //    sb.Append("  FROM " + _tableName + "(nolock) ");
        //    sb.AppendFormat(" WHERE {0}", string.IsNullOrEmpty(_where) ? "1=1" : _where);
        //    return sb.ToString();
        //}
    }
}
